/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

// Wait for the deviceready event before using any of Cordova's device APIs.
// See https://cordova.apache.org/docs/en/latest/cordova/events/events.html#deviceready
document.addEventListener('deviceready', onDeviceReady, false);

// 在浏览器环境中也显示功能卡片导航
document.addEventListener('DOMContentLoaded', function() {
    const featuresContainer = document.getElementById('features-container');
    if (featuresContainer) {
        featuresContainer.style.display = 'block';
    }
});

function onDeviceReady() {
    // Cordova is now initialized. Have fun!

    console.log('Running cordova-' + cordova.platformId + '@' + cordova.version);
    document.getElementById('deviceready').classList.add('ready');

    // 显示功能卡片导航
    const featuresContainer = document.getElementById('features-container');
    if (featuresContainer) {
        featuresContainer.style.display = 'block';
    }

    // 获取并打印设备信息
    console.log("Cordova 设备就绪，开始获取设备信息...");

    // 打印所有核心设备属性
    console.log("设备型号（model）：", device.model);
    console.log("操作系统（platform）：", device.platform);
    console.log("设备唯一标识（uuid）：", device.uuid);
    console.log("系统版本（version）：", device.version);
    console.log("设备制造商（manufacturer）：", device.manufacturer);
    console.log("是否为虚拟设备（isVirtual）：", device.isVirtual);
    console.log("设备序列号（serial）：", device.serial);

    // 在页面上显示设备信息
    displayDeviceInfo();
    
    // 初始化位置信息功能
    initLocationFeature();
    
    // 初始化拍照功能
    initCameraFeature();
    
    // 检查 Camera 插件是否加载
    if (typeof Camera !== 'undefined') {
        console.log('Camera 插件已加载');
        console.log('Camera.DestinationType:', Camera.DestinationType);
        console.log('Camera.PictureSourceType:', Camera.PictureSourceType);
    } else {
        console.warn('Camera 插件未加载，请确保已安装 cordova-plugin-camera');
    }
    
    if (typeof navigator.camera !== 'undefined') {
        console.log('navigator.camera 已就绪');
    } else {
        console.warn('navigator.camera 未定义');
    }
}

function displayDeviceInfo() {
    // 创建设备信息容器
    const deviceInfoContainer = document.createElement('div');
    deviceInfoContainer.id = 'device-info';
    deviceInfoContainer.style.cssText = `
        max-width: 600px;
        margin: 20px auto;
        padding: 20px;
        background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
        border-radius: 12px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    `;

    // 创建标题
    const title = document.createElement('h2');
    title.textContent = '📱 设备信息';
    title.style.cssText = 'color: #2c3e50; margin-bottom: 20px; text-align: center; font-size: 1.5em;';
    deviceInfoContainer.appendChild(title);

    // 创建信息列表
    const infoList = document.createElement('div');
    infoList.style.cssText = 'font-size: 14px; line-height: 1.8;';

    const deviceInfo = [
        { label: '设备型号', value: device.model || '未知' },
        { label: '操作系统', value: device.platform || '未知' },
        { label: '系统版本', value: device.version || '未知' },
        { label: '设备制造商', value: device.manufacturer || '未知' },
        { label: '设备唯一标识', value: device.uuid || '未知' },
        { label: '设备序列号', value: device.serial || '未知' },
        { label: '是否为虚拟设备', value: device.isVirtual !== undefined ? (device.isVirtual ? '是' : '否') : '未知' }
    ];

    deviceInfo.forEach(info => {
        const infoItem = document.createElement('div');
        infoItem.style.cssText = 'margin-bottom: 12px; padding: 12px; background-color: rgba(255,255,255,0.8); border-radius: 8px; transition: transform 0.2s;';
        
        infoItem.addEventListener('mouseenter', function() {
            this.style.transform = 'translateX(5px)';
        });
        infoItem.addEventListener('mouseleave', function() {
            this.style.transform = 'translateX(0)';
        });
        
        const label = document.createElement('strong');
        label.textContent = info.label + '：';
        label.style.cssText = 'color: #2980b9; margin-right: 8px; font-size: 14px;';
        
        const value = document.createElement('span');
        value.textContent = info.value;
        value.style.cssText = 'color: #2c3e50; font-weight: 500;';
        
        infoItem.appendChild(label);
        infoItem.appendChild(value);
        infoList.appendChild(infoItem);
    });

    deviceInfoContainer.appendChild(infoList);

    // 将设备信息添加到页面
    const appDiv = document.querySelector('.app');
    if (appDiv && appDiv.parentNode) {
        appDiv.parentNode.insertBefore(deviceInfoContainer, appDiv.nextSibling);
    } else {
        document.body.appendChild(deviceInfoContainer);
    }
}

// 初始化位置信息功能
function initLocationFeature() {
    // 创建位置信息容器
    const locationContainer = document.createElement('div');
    locationContainer.id = 'location-info';
    locationContainer.style.cssText = `
        max-width: 600px;
        margin: 20px auto;
        padding: 20px;
        background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
        border-radius: 12px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    `;

    // 创建标题
    const title = document.createElement('h2');
    title.textContent = '📍 位置信息';
    title.style.cssText = 'color: #2c3e50; margin-bottom: 20px; text-align: center; font-size: 1.5em;';
    locationContainer.appendChild(title);

    // 创建按钮
    const button = document.createElement('button');
    button.textContent = '获取当前位置';
    button.id = 'get-location-btn';
    button.style.cssText = `
        width: 100%;
        padding: 12px 20px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        border-radius: 6px;
        font-size: 16px;
        font-weight: bold;
        cursor: pointer;
        margin-bottom: 20px;
        transition: transform 0.2s, box-shadow 0.2s;
    `;
    
    button.addEventListener('mouseenter', function() {
        this.style.transform = 'translateY(-2px)';
        this.style.boxShadow = '0 4px 12px rgba(102, 126, 234, 0.4)';
    });
    
    button.addEventListener('mouseleave', function() {
        this.style.transform = 'translateY(0)';
        this.style.boxShadow = 'none';
    });
    
    button.addEventListener('click', getCurrentLocation);
    locationContainer.appendChild(button);

    // 创建位置信息显示区域
    const infoDisplay = document.createElement('div');
    infoDisplay.id = 'location-display';
    infoDisplay.style.cssText = 'font-size: 14px; line-height: 1.8; min-height: 50px;';
    locationContainer.appendChild(infoDisplay);

    // 将位置信息容器添加到页面
    const deviceInfo = document.getElementById('device-info');
    if (deviceInfo && deviceInfo.parentNode) {
        deviceInfo.parentNode.insertBefore(locationContainer, deviceInfo.nextSibling);
    } else {
        document.body.appendChild(locationContainer);
    }
}

// 获取当前位置
function getCurrentLocation() {
    const button = document.getElementById('get-location-btn');
    const display = document.getElementById('location-display');
    
    // 更新按钮状态
    button.disabled = true;
    button.textContent = '定位中...';
    button.style.opacity = '0.7';
    
    // 清空之前的显示
    display.innerHTML = '<p style="color: #666; text-align: center;">正在获取位置信息...</p>';

    // 调用获取当前位置方法
    navigator.geolocation.getCurrentPosition(
        // 成功回调：获取位置信息
        function (position) {
            console.log("定位成功，位置信息如下：");
            console.log("纬度：", position.coords.latitude);
            console.log("经度：", position.coords.longitude);
            console.log("定位精度：", position.coords.accuracy + " 米");
            console.log("海拔：", position.coords.altitude !== null && position.coords.altitude !== undefined ? position.coords.altitude : "不支持");
            console.log("海拔精度：", position.coords.altitudeAccuracy !== null && position.coords.altitudeAccuracy !== undefined ? position.coords.altitudeAccuracy : "不支持");
            
            // 处理时间戳输出
            if (position.timestamp && position.timestamp > 0) {
                const timestamp = position.timestamp > 1000000000000 ? position.timestamp : position.timestamp * 1000;
                console.log("定位时间：", new Date(timestamp).toLocaleString('zh-CN'));
            } else {
                console.log("定位时间：", new Date().toLocaleString('zh-CN') + " (使用当前时间)");
            }
            console.log("原始timestamp值：", position.timestamp);

            // 在页面上显示位置信息
            displayLocationInfo(position);
            
            // 恢复按钮状态
            button.disabled = false;
            button.textContent = '重新获取位置';
            button.style.opacity = '1';
        },
        // 失败回调：处理定位错误
        function (error) {
            console.error("定位失败：");
            let errorMessage = "";
            
            switch (error.code) {
                case error.PERMISSION_DENIED:
                    console.error("错误码 1：用户拒绝授予定位权限");
                    errorMessage = "错误码 1：用户拒绝授予定位权限";
                    break;
                case error.POSITION_UNAVAILABLE:
                    console.error("错误码 2：位置信息不可用（如设备无GPS信号）");
                    errorMessage = "错误码 2：位置信息不可用（如设备无GPS信号）";
                    break;
                case error.TIMEOUT:
                    console.error("错误码 3：定位请求超时");
                    errorMessage = "错误码 3：定位请求超时";
                    break;
                default:
                    console.error("错误码 4：未知错误");
                    errorMessage = "错误码 4：未知错误";
                    break;
            }
            
            // 显示错误信息
            display.innerHTML = `
                <div style="padding: 15px; background-color: #fee; border-radius: 4px; border-left: 4px solid #f00;">
                    <p style="color: #c00; margin: 0; font-weight: bold;">定位失败</p>
                    <p style="color: #666; margin: 5px 0 0 0;">${errorMessage}</p>
                </div>
            `;
            
            // 恢复按钮状态
            button.disabled = false;
            button.textContent = '获取当前位置';
            button.style.opacity = '1';
        },
        // 配置选项：自定义定位参数
        {
            enableHighAccuracy: true, // 是否启用高精度定位（GPS），true=高精度（耗电），false=低精度（网络定位）
            timeout: 15000, // 定位超时时间（毫秒），超过时间未获取位置则触发失败回调
            maximumAge: 0 // 位置缓存有效期（毫秒），0=不使用缓存，30000=允许使用30秒内的缓存位置
        }
    );
}

// 显示位置信息
function displayLocationInfo(position) {
    const display = document.getElementById('location-display');
    
    // 处理时间戳：检查timestamp是否存在且有效
    let locationTime = '未知';
    if (position.timestamp && position.timestamp > 0) {
        // timestamp可能是毫秒数
        const timestamp = position.timestamp > 1000000000000 ? position.timestamp : position.timestamp * 1000;
        locationTime = new Date(timestamp).toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
        });
    } else {
        // 如果timestamp无效，使用当前时间
        locationTime = new Date().toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
        });
    }
    
    // 处理海拔：检查是否为null/undefined，以及是否为有效数值
    let altitudeValue = '不支持';
    if (position.coords.altitude !== null && position.coords.altitude !== undefined && !isNaN(position.coords.altitude)) {
        altitudeValue = position.coords.altitude.toFixed(2) + ' 米';
    }
    
    // 处理海拔精度：检查是否为null/undefined，以及是否为有效数值
    let altitudeAccuracyValue = '不支持';
    if (position.coords.altitudeAccuracy !== null && position.coords.altitudeAccuracy !== undefined && !isNaN(position.coords.altitudeAccuracy)) {
        altitudeAccuracyValue = position.coords.altitudeAccuracy.toFixed(2) + ' 米';
    }
    
    const locationInfo = [
        { label: '纬度', value: position.coords.latitude.toFixed(6) + '°' },
        { label: '经度', value: position.coords.longitude.toFixed(6) + '°' },
        { label: '定位精度', value: position.coords.accuracy ? (position.coords.accuracy.toFixed(2) + ' 米') : '未知' },
        { label: '海拔', value: altitudeValue },
        { label: '海拔精度', value: altitudeAccuracyValue },
        { label: '定位时间', value: locationTime }
    ];

    let html = '';
    locationInfo.forEach(info => {
        html += `
            <div style="margin-bottom: 10px; padding: 8px; background-color: #f8f9fa; border-radius: 4px;">
                <strong style="color: #2980b9; margin-right: 8px;">${info.label}：</strong>
                <span style="color: #555;">${info.value}</span>
            </div>
        `;
    });
    
    // 添加地图链接（可选）
    html += `
        <div style="margin-top: 15px; text-align: center;">
            <a href="https://www.openstreetmap.org/?mlat=${position.coords.latitude}&mlon=${position.coords.longitude}&zoom=15" 
               target="_blank" 
               style="display: inline-block; padding: 8px 16px; background-color: #3498db; color: white; text-decoration: none; border-radius: 4px;">
                在地图上查看
            </a>
        </div>
    `;
    
    display.innerHTML = html;
}

// 初始化拍照功能
function initCameraFeature() {
    // 创建拍照功能容器
    const cameraContainer = document.createElement('div');
    cameraContainer.id = 'camera-info';
    cameraContainer.style.cssText = `
        max-width: 600px;
        margin: 20px auto;
        padding: 20px;
        background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
        border-radius: 12px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    `;

    // 创建标题
    const title = document.createElement('h2');
    title.textContent = '📷 拍照功能';
    title.style.cssText = 'color: #2c3e50; margin-bottom: 20px; text-align: center; font-size: 1.5em;';
    cameraContainer.appendChild(title);

    // 创建按钮容器
    const buttonContainer = document.createElement('div');
    buttonContainer.style.cssText = 'display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap;';

    // 前置摄像头拍照按钮
    const frontCameraBtn = createCameraButton('前置摄像头拍照', 'front');
    buttonContainer.appendChild(frontCameraBtn);

    // 后置摄像头拍照按钮
    const backCameraBtn = createCameraButton('后置摄像头拍照', 'back');
    buttonContainer.appendChild(backCameraBtn);

    // 从相册选择按钮
    const photoLibraryBtn = createCameraButton('从相册选择', 'library');
    buttonContainer.appendChild(photoLibraryBtn);

    cameraContainer.appendChild(buttonContainer);

    // 创建图片显示区域
    const imageDisplay = document.createElement('div');
    imageDisplay.id = 'camera-display';
    imageDisplay.style.cssText = 'font-size: 14px; line-height: 1.8; min-height: 50px; text-align: center;';
    cameraContainer.appendChild(imageDisplay);

    // 将拍照功能容器添加到页面
    const locationInfo = document.getElementById('location-info');
    if (locationInfo && locationInfo.parentNode) {
        locationInfo.parentNode.insertBefore(cameraContainer, locationInfo.nextSibling);
    } else {
        const deviceInfo = document.getElementById('device-info');
        if (deviceInfo && deviceInfo.parentNode) {
            deviceInfo.parentNode.insertBefore(cameraContainer, deviceInfo.nextSibling);
        } else {
            document.body.appendChild(cameraContainer);
        }
    }
}

// 创建拍照按钮
function createCameraButton(text, type) {
    const button = document.createElement('button');
    button.textContent = text;
    button.style.cssText = `
        flex: 1;
        min-width: 120px;
        padding: 12px 20px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        border-radius: 6px;
        font-size: 14px;
        font-weight: bold;
        cursor: pointer;
        transition: transform 0.2s, box-shadow 0.2s;
    `;
    
    button.addEventListener('mouseenter', function() {
        this.style.transform = 'translateY(-2px)';
        this.style.boxShadow = '0 4px 12px rgba(102, 126, 234, 0.4)';
    });
    
    button.addEventListener('mouseleave', function() {
        this.style.transform = 'translateY(0)';
        this.style.boxShadow = 'none';
    });
    
    button.addEventListener('click', function() {
        if (type === 'front') {
            openCamera('FRONT');
        } else if (type === 'back') {
            openCamera('BACK');
        } else if (type === 'library') {
            openPhotoLibrary();
        }
    });
    
    return button;
}

// 打开摄像头拍照（前置/后置）
function openCamera(direction) {
    const display = document.getElementById('camera-display');
    
    // 检查 Camera 插件是否可用
    if (typeof Camera === 'undefined') {
        console.error('Camera 插件未加载');
        display.innerHTML = `
            <div style="padding: 15px; background-color: #fee; border-radius: 4px; border-left: 4px solid #f00;">
                <p style="color: #c00; margin: 0; font-weight: bold;">错误</p>
                <p style="color: #666; margin: 5px 0 0 0;">Camera 插件未加载，请确保已安装 cordova-plugin-camera 插件</p>
            </div>
        `;
        return;
    }
    
    if (typeof navigator.camera === 'undefined') {
        console.error('navigator.camera 未定义');
        display.innerHTML = `
            <div style="padding: 15px; background-color: #fee; border-radius: 4px; border-left: 4px solid #f00;">
                <p style="color: #c00; margin: 0; font-weight: bold;">错误</p>
                <p style="color: #666; margin: 5px 0 0 0;">navigator.camera 未定义，请等待设备就绪</p>
            </div>
        `;
        return;
    }
    
    display.innerHTML = '<p style="color: #666; text-align: center;">正在打开摄像头...</p>';

    var options = {
        quality: 100,
        destinationType: Camera.DestinationType.FILE_URI,
        sourceType: Camera.PictureSourceType.CAMERA,
        encodingType: Camera.EncodingType.JPEG,
        mediaType: Camera.MediaType.PICTURE,
        allowEdit: true,
        cameraDirection: direction === 'FRONT' ? Camera.Direction.FRONT : Camera.Direction.BACK,
        correctOrientation: true,
        saveToPhotoAlbum: true
    };

    console.log('调用摄像头，参数：', options);
    
    navigator.camera.getPicture(
        function cameraSuccess(imageUri) {
            console.log('拍照成功，图片路径：', imageUri);
            displayCameraImage(imageUri, '拍照');
        },
        function cameraError(error) {
            console.error('拍照失败：', error);
            let errorMsg = error;
            if (typeof error === 'string') {
                errorMsg = error;
            } else if (error && error.message) {
                errorMsg = error.message;
            }
            display.innerHTML = `
                <div style="padding: 15px; background-color: #fee; border-radius: 4px; border-left: 4px solid #f00;">
                    <p style="color: #c00; margin: 0; font-weight: bold;">拍照失败</p>
                    <p style="color: #666; margin: 5px 0 0 0;">${errorMsg}</p>
                </div>
            `;
        },
        options
    );
}

// 从相册选择图片
function openPhotoLibrary() {
    const display = document.getElementById('camera-display');
    
    // 检查 Camera 插件是否可用
    if (typeof Camera === 'undefined') {
        console.error('Camera 插件未加载');
        display.innerHTML = `
            <div style="padding: 15px; background-color: #fee; border-radius: 4px; border-left: 4px solid #f00;">
                <p style="color: #c00; margin: 0; font-weight: bold;">错误</p>
                <p style="color: #666; margin: 5px 0 0 0;">Camera 插件未加载，请确保已安装 cordova-plugin-camera 插件</p>
            </div>
        `;
        return;
    }
    
    if (typeof navigator.camera === 'undefined') {
        console.error('navigator.camera 未定义');
        display.innerHTML = `
            <div style="padding: 15px; background-color: #fee; border-radius: 4px; border-left: 4px solid #f00;">
                <p style="color: #c00; margin: 0; font-weight: bold;">错误</p>
                <p style="color: #666; margin: 5px 0 0 0;">navigator.camera 未定义，请等待设备就绪</p>
            </div>
        `;
        return;
    }
    
    display.innerHTML = '<p style="color: #666; text-align: center;">正在打开相册...</p>';

    var options = {
        quality: 80,
        destinationType: Camera.DestinationType.DATA_URL,
        sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
        encodingType: Camera.EncodingType.JPEG,
        mediaType: Camera.MediaType.PICTURE,
        targetWidth: 800,
        targetHeight: 600,
        allowEdit: true,
        correctOrientation: true
    };

    console.log('调用相册，参数：', options);

    navigator.camera.getPicture(
        function cameraSuccess(imageData) {
            console.log('选择图片成功');
            displayCameraImage('data:image/jpeg;base64,' + imageData, '相册');
        },
        function cameraError(error) {
            console.error('选择图片失败：', error);
            let errorMsg = error;
            if (typeof error === 'string') {
                errorMsg = error;
            } else if (error && error.message) {
                errorMsg = error.message;
            }
            display.innerHTML = `
                <div style="padding: 15px; background-color: #fee; border-radius: 4px; border-left: 4px solid #f00;">
                    <p style="color: #c00; margin: 0; font-weight: bold;">选择图片失败</p>
                    <p style="color: #666; margin: 5px 0 0 0;">${errorMsg}</p>
                </div>
            `;
        },
        options
    );
}

// 显示图片
function displayCameraImage(imageUri, source) {
    const display = document.getElementById('camera-display');
    
    const img = document.createElement('img');
    img.src = imageUri;
    img.style.cssText = `
        max-width: 100%;
        height: auto;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        margin-bottom: 10px;
    `;
    
    img.onload = function() {
        const info = document.createElement('div');
        info.style.cssText = 'color: #666; font-size: 12px; margin-top: 10px;';
        info.innerHTML = `
            <p>来源：${source}</p>
            <p>尺寸：${this.naturalWidth} x ${this.naturalHeight} 像素</p>
            <p>路径：${imageUri.length > 50 ? imageUri.substring(0, 50) + '...' : imageUri}</p>
        `;
        
        display.innerHTML = '';
        display.appendChild(img);
        display.appendChild(info);
    };
    
    img.onerror = function() {
        display.innerHTML = `
            <div style="padding: 15px; background-color: #fee; border-radius: 4px; border-left: 4px solid #f00;">
                <p style="color: #c00; margin: 0; font-weight: bold;">图片加载失败</p>
                <p style="color: #666; margin: 5px 0 0 0;">无法显示图片：${imageUri}</p>
            </div>
        `;
    };
}
